﻿using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Spire.Xls;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using WebsocketDemo.Controllers;
using WebsocketDemo.Mode;

namespace WebsocketDemo.UniverjsEditing
{
    public class UniverjsEditing: Hub
    {
        static Dictionary<string, object> dic=new Dictionary<string, object>();
   
        /// <summary>
        /// 发送消息-所有人
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendAllMessage(string message)
        {
            await Clients.All.SendAsync("SendAllMessage", $"{message}");
        }
        /// <summary>
        /// 发送消息-所有人
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendOtherMessage(string message)
        {
            await Clients.Others.SendAsync("SendOtherMessage", $"{message}");
        }
        /// <summary>
        /// 接受消息并回发消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendMessageToServer(string message)
        {
            await SendOtherMessage(message);
            // 示例：将接收到的消息回发给发送者，模拟服务器响应
            await Clients.Caller.SendAsync("ReceiveServerResponse", $"成功");
        }


        /// <summary>
        /// 接受加载消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task GetLoadData(string message)
        {
            var a = Context.UserIdentifier;
            var b = Context.User;
            //映射人员ID和链接的,demo不用管
            var ddd=Clients.Others;
           
            if (dic.TryGetValue(Context.ConnectionId,out object? val))
            {
                dic[Context.ConnectionId] = message;
            }
            else
            {
                dic.TryAdd(Context.ConnectionId, message);
            }
            var otherconnectionID= dic.FirstOrDefault(x=>x.Key.ToString()!= Context.ConnectionId).Key?.ToString();
            string outdata = "";
            UniverExcelModel model = new UniverExcelModel();
            //不存在就证明没有正在编辑的界面,就获取加载的内容
            if (otherconnectionID == null)
            {
                JsonSerializerSettings setting = new JsonSerializerSettings();
                setting.Formatting = Formatting.None;
                setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
                setting.NullValueHandling = NullValueHandling.Ignore;
                outdata = JsonConvert.SerializeObject(WeatherForecastController.Model11, setting);
                await Clients.Caller.SendAsync("ReceiveLoad", $"{outdata}");

            }
            //存在就证明有正在编辑的界面,就获取正在编辑的内容
            else
            {
                await Clients.Client(otherconnectionID).SendAsync("GetLoadDataCache", $"{Context.ConnectionId}");
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task SendLoadDataCache (string message)
        {
            JObject data = JsonConvert.DeserializeObject<JObject>(message);
            var semdcontentid=data.SelectToken("connectionId").Value<string>();
            var senddata = data.SelectToken("data").Value<dynamic>();
            JsonSerializerSettings setting = new JsonSerializerSettings();
            setting.Formatting = Formatting.None;
            setting.ContractResolver = new CamelCasePropertyNamesContractResolver();
            setting.NullValueHandling = NullValueHandling.Ignore;
            await Clients.Client(semdcontentid).SendAsync("ReceiveLoad", $"{JsonConvert.SerializeObject(senddata, setting)}");
        }

        public  void SaveData(string message)
        {

            return;
        }
        

        public override Task OnDisconnectedAsync(Exception? exception)
        {
            // 当客户端断开连接时，从组中移除或进行其他清理
            if (dic.TryGetValue(Context.ConnectionId, out object datavalue))
            {
                dic.Remove(Context.ConnectionId);
            }
            return base.OnDisconnectedAsync(exception);
        }

    }
}
